<template>
  <!-- 患者药房 -->
  <section>
    <div style="border-bottom:1px solid #eee;padding-bottom:10px;">
      <el-page-header @back="goBack" content="发药"></el-page-header>
    </div>
    <br />
    <div class="patient-layout">
      <div>
        <patientBasicInfo :cureId="form.cureId" :patientId="patientId" @init="onPatienInit"></patientBasicInfo>
      </div>
      <div v-if="dataInfo">
        <!-- <table border="0" width="100%">
          <tr>
            <td>
              <h3 style="margin:0;">发药</h3>
            </td>
            <td style="text-align:right;">
              <el-button @click="$router.push('pharmacyindex')">
                <i class="el-icon-arrow-left"></i>
                <span>返回</span>
              </el-button>
            </td>
          </tr>
        </table>
        <br>-->
        <table width="100%" border="0" style="table-layout: fixed;">
          <tr>
            <td>开单医生：{{ dataInfo.doctorName }}</td>
            <td style="text-align:center;">开单时间：{{ dataInfo.time }}</td>
            <td style="text-align:right;">所属科室：{{ dataInfo.deptName }}</td>
          </tr>
        </table>

        <br />
        <el-alert type="warning" :closable="false">
          <table slot="title" width="100%" border="0">
            <tr>
              <td>过敏史：</td>
              <td>
                <div v-if="guoMinArr.length == 0">否认</div>
                <div v-else>
                  <span v-for="(item, index) in guoMinArr" :key="index" style="margin-right:10px;">
                    {{ item.allergens }},{{ item.allergicReaction }},{{
                    item.allergicDegree
                    }}
                  </span>
                </div>
              </td>
            </tr>
          </table>
        </el-alert>
        <br />
        <table class="table-box">
          <thead>
            <tr>
              <th></th>
              <th>药品名称</th>
              <th>生产厂家</th>
              <th>规格</th>
              <th>(次)剂量</th>
              <th>用法</th>
              <th>用药频次</th>
              <th>天数</th>
              <th>数量</th>
              <th>说明</th>
              <th>取药地点</th>
              <th>收费状态</th>
              <th>发药状态</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-if="dataInfo.cureWesternPrescriptionDrugVOS.length > 0"
              style="background-color: #f5f5f5;"
            >
              <td colspan="13">
                <div class="form-tool" style="align-items: center;">
                  <div>
                    <i class="vertical-middle el-icon-caret-bottom"></i>
                    <span class="vertical-middle">西/成药</span>
                  </div>
                  <div>
                    <el-button @click="onRecipePint('xi')">打印处方单</el-button>
                    <el-button @click="onPint('xi')">打印发药单</el-button>
                    <el-button
                      type="primary"
                      @click="
                        onSendDrug(
                          dataInfo.cureWesternPrescriptionDrugVOS,
                          'xy'
                        )
                      "
                    >发药</el-button>
                  </div>
                </div>
              </td>
            </tr>
            <tr
              v-for="(item, index) in dataInfo.cureWesternPrescriptionDrugVOS"
              :key="index + 'xy'"
            >
              <td>
                <el-checkbox v-model="item.check"></el-checkbox>
              </td>
              <td>
                {{ item.medicalDrugVO.drugName }}
                <span
                  :class="item.medicalDrugVO.highWarning == 1 ? 'hight' : ''"
                >
                  {{
                  item.medicalDrugVO.highWarning == 1 ? "(高危药品！)" : ""
                  }}
                </span>
                <span class="antibacterial">
                  {{
                  item.medicalDrugVO.antibacterial == 1 ? "(抗菌药物)" : "(非抗菌药物)"
                  }}
                </span>
              </td>
              <td>{{ item.medicalDrugVO.factory }}</td>
              <td>{{ item.medicalDrugVO.specs }}</td>
              <td>
                {{ item.oneDose
                }}{{ item.oneDoseUnit | changeAssist(unitEnum) }}
              </td>
              <td>{{ item.use | changeAssist(useEnum) }}</td>
              <td>{{ item.frequency | changeAssist(frequencyEnum) }}</td>
              <td>{{ item.useDay }}</td>
              <td>{{ item.useTotal }}{{ item.totalUnit | changeAssist(unitEnum) }}</td>
              <td>
                <div style="max-width:300px;">{{ item.remark }}</div>
              </td>
              <td>{{ item.getAddress | changeAssist(getAddressEnum) }}</td>
              <td>
                <span v-if="item.payStatus == 1" class="primary-color">已收费</span>
                <span v-else class="error-color">未收费</span>
              </td>
              <td>
                <span v-if="item.status == 1" class="primary-color">已发药</span>
                <span v-else class="error-color">未发药</span>
              </td>
            </tr>
            <template v-if="dataInfo.cureTraditionalPrescriptionDrugVOS.length > 0">
              <template v-for="(it, i) in dataInfo.cureTraditionalPrescriptionDrugVOS">
                <tr v-if="it.length != 0" :key="it.id" style="background-color: #f5f5f5;">
                  <td colspan="13">
                    <div class="form-tool" style="align-items: center;">
                      <div>
                        <i class="vertical-middle el-icon-caret-bottom"></i>
                        <span class="vertical-middle">中药{{ i > 0 ? i : "" }}</span>
                      </div>
                      <div>
                        <el-button @click="onPint('zhong', it)">打印发药单</el-button>
                        <el-button type="primary" @click="onSendDrug(it, 'zy')">发药</el-button>
                      </div>
                    </div>
                  </td>
                </tr>
                <tr v-for="(item, index) in it" :key="index + 'zy' + i">
                  <td>
                    <el-checkbox v-model="item.check"></el-checkbox>
                  </td>
                  <td>{{ item.medicalDrugVO.drugName }}</td>
                  <td>{{ item.medicalDrugVO.factory }}</td>
                  <td>{{ item.medicalDrugVO.specs }}</td>
                  <td>
                    {{ item.oneDose
                    }}{{ item.oneDoseUnit | changeAssist(unitEnum) }}
                  </td>
                  <td>{{ item.use | changeAssist(useEnum) }}</td>
                  <td>{{ item.frequency | changeAssist(frequencyEnum) }}</td>
                  <td>{{ item.useDay }}</td>
                  <td>
                    {{ item.useTotal
                    }}{{ item.totalUnit | changeAssist(unitEnum) }}
                  </td>
                  <td>
                    <div style="max-width:300px;">{{ item.remark }}</div>
                  </td>
                  <td>{{ item.getAddress | changeAssist(getAddressEnum) }}</td>
                  <td>
                    <span v-if="item.payStatus == 1" class="primary-color">已收费</span>
                    <span v-else class="error-color">未收费</span>
                  </td>
                  <td>
                    <span v-if="item.status == 1" class="primary-color">已发药</span>
                    <span v-else class="error-color">未发药</span>
                  </td>
                </tr>
              </template>
            </template>
          </tbody>
        </table>
        <!-- <br>
        <div>
          <el-button @click="onOpenDrugBatch" type='primary'>保存</el-button>
        </div>-->
        <dialogDrugBatch v-model="dialogDrugBatch" :queryData="queryData" @success="onSendSuccess"></dialogDrugBatch>
        <iframe ref="iframe1" frameborder="0" height="0px" width="0px" src="/print/sendDrug.html"></iframe>
        <westwardPrint
          v-model="dialogWestwardPrint"
          :cureId="form.cureId"
          :patientSignInfo="patientSignInfo"
        ></westwardPrint>
      </div>
    </div>
  </section>
</template>
<script>
export default {
  components: {
    patientBasicInfo: () => import("@/pages/_com/patientBasicInfo.vue"),
    dialogDrugBatch: () => import("./_com/dialogDrugBatch.vue"),
    westwardPrint: () => import("@/pages/_com/dialogWestwardPrint.vue"),
  },
  data() {
    return {
      dialogWestwardPrint: false,
      dialogDrugBatch: false,
      qxBtns: {},
      cureFirstVisitRecord: null, //初步诊断
      form: {
        cureId: "",
        status: "",
      },
      patientId: "",
      patientInfo: null,
      patientSignInfo: null,
      dataInfo: null,
      guoMinArr: [],
      unitEnum: [],
      useEnum: [],
      frequencyEnum: [],
      getAddressEnum: [],
      // payStatusEnum:[],
      queryData: {
        zy: [],
        xy: [],
        type: "xy", //当前发药类型
      },
      curItem: null,
    };
  },
  created() {
    let th = this;
    let query = th.$route.query;
    let fn = async function () {
      // th.payStatusEnum = await th.("支付状态");
      th.unitEnum = await th.getCommonConfigByKey("药品剂量单位");
      th.useEnum = await th.getCommonConfigByKey("药品用法");
      th.frequencyEnum = await th.getCommonConfigByKey("药品频次");
      th.getAddressEnum = await th.getCommonConfigByKey("取药地");
      th.$store.commit("Set_doctorMzEnum", { doseUnitEnum: th.unitEnum });
      th.$store.commit("Set_doctorMzEnum", { useEnum: th.useEnum });
      th.$store.commit("Set_doctorMzEnum", { frequencyEnum: th.frequencyEnum });
      th.getData();
    };
    th.verifyUrlAttack(query).then((res) => {
      th.form.cureId = th.jieMi(query.cureId);
      th.patientId = th.jieMi(query.patientId);
      th.form.status = query.status;
      th.getQX();
      th.getDataBi();
      fn();
    });
  },
  methods: {
    //发药成功
    onSendSuccess(arr) {
      const th = this;
      th.curItem.forEach((item) => {
        let data = arr.find((d) => {
          return d == item.id;
        });
        if (data) {
          item.status = 1;
        }
      });
    },
    //选择药品发药（新）
    onSendDrug(array, type) {
      const th = this;
      let xyids = [];
      let zyids = [];
      if (!th.dataInfo) return;
      th.curItem = array;
      th.queryData.type = type;
      if (type == "xy") {
        //西药
        array.forEach((item) => {
          if (item.check && item.status != 1) {
            xyids.push({
              prescriptionDrugId: item.id,
              totalUnit: item.totalUnit,
              useTotal: item.useTotal,
            });
          }
        });
        if (xyids.length == 0) {
          th.$message.warning("您未勾选数据或勾选了已发药品");
          return;
        }
      } else {
        array.forEach((d) => {
          if (d.check && d.status != 1) {
            zyids.push({
              prescriptionDrugId: d.id,
              totalUnit: d.totalUnit,
              useTotal: d.useTotal,
            });
          }
        });
        if (zyids.length == 0) {
          th.$message.warning("您未勾选数据或勾选了已发药品");
          return;
        }
      }
      th.queryData.zy = zyids;
      th.queryData.xy = xyids;
      th.dialogDrugBatch = true;
    },
    //选择药品(废弃)
    onOpenDrugBatch() {
      let th = this;
      let xyids = [];
      let zyids = [];
      if (!th.dataInfo) return;
      let bo = false;
      th.dataInfo.cureWesternPrescriptionDrugVOS.forEach((item) => {
        if (item.check && item.status != 1) {
          xyids.push({
            prescriptionDrugId: item.id,
            totalUnit: item.totalUnit,
            useTotal: item.useTotal,
          });
          bo = true;
        }
      });
      th.dataInfo.cureTraditionalPrescriptionDrugVOS.forEach((item) => {
        item.forEach((d) => {
          if (d.check && d.status != 1) {
            zyids.push({
              prescriptionDrugId: d.id,
              totalUnit: d.totalUnit,
              useTotal: d.useTotal,
            });
            bo = true;
          }
        });
      });
      if (!bo) {
        th.$message.warning("未选择发药数据或勾选了已发药品");
        return;
      }
      th.queryData.zy = zyids;
      th.queryData.xy = xyids;
      th.dialogDrugBatch = true;
    },
    getData() {
      let th = this;
      let j = {};
      Object.assign(j, th.form);
      th.$api.curePrescriptiondispensingDrug(j).then((res) => {
        if (res.executed) {
          let d = res.data || {};
          if (d.cureWesternPrescriptionDrugVOS) {
            d.cureWesternPrescriptionDrugVOS.forEach((d2) => {
              d2.check = true;
            });
          }
          if (d.cureTraditionalPrescriptionDrugVOS) {
            d.cureTraditionalPrescriptionDrugVOS.forEach((d2) => {
              d2.forEach((d3) => {
                d3.check = true;
              });
            });
          }
          th.dataInfo = res.data;
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    //获取病历
    getDataBi() {
      let th = this;
      let j = {
        cureId: th.form.cureId,
      };
      th.$api.getCureMedicalDetailId(j).then((res) => {
        if (res.executed) {
          // //初步诊断
          // cureFirstVisitRecord: null,
          // //病历信息
          // cureMedical: null,
          // //过敏史
          // curePatientAllergy: null,
          // //既往，个人，疫苗
          // curePatientHistory: null
          let d = res.data.curePatientAllergy;
          if (d && res.data.curePatientAllergy.length > 0) th.guoMinArr = d;
        }
      });
    },
    //患者初始化完成
    onPatienInit(patientInfo, signInfo) {
      let th = this;
      th.patientInfo = patientInfo;
      th.patientSignInfo = signInfo;
    },
    //打印
    onPint(type, arr) {
      let th = this;
      let j = {
        type: type,
        doseUnitEnum: th.unitEnum,
        useEnum: th.useEnum,
        frequencyEnum: th.frequencyEnum,
        operatorUser: th.adminUser.memberName,
        hospital: {
          name: th.adminUser.hospitalName,
          logo: th.adminUser.printLogo,
          time: th.dataInfo.time,
          doctor: th.dataInfo.doctorName,
          professionalDeptName: th.dataInfo.professionalDeptName,
        },
        patient: th.patientInfo,
        drug: [],
      };
      //西药打印
      if (type == "xi") {
        th.dataInfo.cureWesternPrescriptionDrugVOS.forEach((d) => {
          if (d.check) {
            j.drug.push(d);
          }
        });
        if (j.drug.length == 0) {
          th.$message.warning("请先勾选西药");
          return;
        }
      } else {
        arr.forEach((d) => {
          if (d.check) {
            j.drug.push(d);
          }
        });
        if (j.drug.length == 0) {
          th.$message.warning("请先勾选中药");
          return;
        }
      }
      th.$refs["iframe1"].contentWindow.postMessage(
        j,
        `${window.location.origin}/print/sendDrug.html`
      );
    },
    onRecipePint(type) {
      const th = this;
      th.dialogWestwardPrint = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.hight {
  color: #e6a23c;
  margin-left: 10px;
}
.antibacterial {
  margin-left: 10px;
  color: #409eff;
}
</style>
